package com.example.controller;

import com.example.model.LaundryOrder;
import com.example.model.User;
import com.example.service.LaundryOrderService;
import com.example.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/merchant")
@Tag(name = "商家端管理", description = "商家端专用接口")
public class MerchantController {
    
    @Autowired
    private LaundryOrderService laundryOrderService;
    
    @Autowired
    private UserService userService;

    // ==================== 商家仪表板 ====================
    @GetMapping("/dashboard")
    @Operation(summary = "获取商家仪表板数据")
    public ResponseEntity<Map<String, Object>> getMerchantDashboard() {
        Map<String, Object> dashboard = new HashMap<>();
        
        // 订单统计
        LaundryOrderService.OrderStatistics orderStats = laundryOrderService.getOrderStatistics();
        dashboard.put("totalOrders", orderStats.getTotalOrders());
        dashboard.put("todayOrders", orderStats.getTodayOrders());
        dashboard.put("pendingOrders", orderStats.getPendingOrders());
        dashboard.put("todayRevenue", orderStats.getTodayRevenue());
        
        // 商家特定统计
        dashboard.put("completedOrders", 0L); // 这里应该根据商家ID统计
        dashboard.put("processingOrders", 0L);
        dashboard.put("customerCount", 0L);
        dashboard.put("averageRating", 4.5);
        
        return ResponseEntity.ok(dashboard);
    }

    // ==================== 商家订单管理 ====================
    @GetMapping("/orders")
    @Operation(summary = "获取商家订单列表")
    public ResponseEntity<Page<LaundryOrder>> getMerchantOrders(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "createdAt") String sortBy,
            @RequestParam(defaultValue = "desc") String sortDir,
            @RequestParam(required = false) String status) {
        
        Sort sort = Sort.by(Sort.Direction.fromString(sortDir), sortBy);
        Pageable pageable = PageRequest.of(page, size, sort);
        
        // 这里应该根据当前商家ID过滤订单
        if (status != null && !status.isEmpty()) {
            try {
                LaundryOrder.OrderStatus orderStatus = LaundryOrder.OrderStatus.valueOf(status.toUpperCase());
                return ResponseEntity.ok(laundryOrderService.findByStatus(orderStatus, pageable));
            } catch (IllegalArgumentException e) {
                return ResponseEntity.badRequest().build();
            }
        }
        
        return ResponseEntity.ok(laundryOrderService.findAll(pageable));
    }

    @GetMapping("/orders/{id}")
    @Operation(summary = "获取商家订单详情")
    public ResponseEntity<LaundryOrder> getMerchantOrderDetail(@PathVariable Long id) {
        return laundryOrderService.findById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @PutMapping("/orders/{id}/status")
    @Operation(summary = "更新商家订单状态")
    public ResponseEntity<LaundryOrder> updateMerchantOrderStatus(
            @PathVariable Long id,
            @RequestBody Map<String, Object> statusUpdate) {
        
        String status = (String) statusUpdate.get("status");
        String notes = (String) statusUpdate.get("notes");
        
        try {
            LaundryOrder.OrderStatus orderStatus = LaundryOrder.OrderStatus.valueOf(status.toUpperCase());
            LaundryOrder updatedOrder = laundryOrderService.updateOrderStatus(id, orderStatus);
            
            if (notes != null && !notes.isEmpty()) {
                updatedOrder.setNotes(notes);
                updatedOrder = laundryOrderService.updateOrder(updatedOrder);
            }
            
            return ResponseEntity.ok(updatedOrder);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }

    @PostMapping("/orders/{id}/accept")
    @Operation(summary = "接受订单")
    public ResponseEntity<LaundryOrder> acceptOrder(@PathVariable Long id) {
        try {
            LaundryOrder order = laundryOrderService.updateOrderStatus(id, LaundryOrder.OrderStatus.CONFIRMED);
            return ResponseEntity.ok(order);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }

    @PostMapping("/orders/{id}/reject")
    @Operation(summary = "拒绝订单")
    public ResponseEntity<LaundryOrder> rejectOrder(
            @PathVariable Long id,
            @RequestBody Map<String, String> rejectData) {
        
        try {
            String reason = rejectData.get("reason");
            LaundryOrder order = laundryOrderService.cancelOrder(id, reason);
            return ResponseEntity.ok(order);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }

    // ==================== 商家客户管理 ====================
    @GetMapping("/customers")
    @Operation(summary = "获取商家客户列表")
    public ResponseEntity<Page<User>> getMerchantCustomers(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        Pageable pageable = PageRequest.of(page, size, Sort.by("createdAt").descending());
        
        // 这里应该根据商家ID过滤客户
        Page<User> customers = userService.getUsersByRole(User.UserRole.CUSTOMER, pageable);
        return ResponseEntity.ok(customers);
    }

    @GetMapping("/customers/{id}")
    @Operation(summary = "获取商家客户详情")
    public ResponseEntity<User> getMerchantCustomerDetail(@PathVariable Long id) {
        return userService.getUserById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    // ==================== 商家员工管理 ====================
    @GetMapping("/staff")
    @Operation(summary = "获取商家员工列表")
    public ResponseEntity<Page<User>> getMerchantStaff(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        Pageable pageable = PageRequest.of(page, size, Sort.by("createdAt").descending());
        
        // 这里应该根据商家ID过滤员工
        Page<User> staff = userService.getUsersByRole(User.UserRole.WORKER, pageable);
        return ResponseEntity.ok(staff);
    }

    @PostMapping("/staff")
    @Operation(summary = "添加商家员工")
    public ResponseEntity<User> addMerchantStaff(@RequestBody User staff) {
        staff.setRole(User.UserRole.WORKER);
        User createdStaff = userService.createUser(staff);
        return ResponseEntity.ok(createdStaff);
    }

    @PutMapping("/staff/{id}")
    @Operation(summary = "更新商家员工")
    public ResponseEntity<User> updateMerchantStaff(
            @PathVariable Long id,
            @RequestBody User staff) {
        
        return userService.getUserById(id)
                .map(existingStaff -> {
                    staff.setId(id);
                    User updatedStaff = userService.updateUser(staff);
                    return ResponseEntity.ok(updatedStaff);
                })
                .orElse(ResponseEntity.notFound().build());
    }

    @DeleteMapping("/staff/{id}")
    @Operation(summary = "删除商家员工")
    public ResponseEntity<Void> deleteMerchantStaff(@PathVariable Long id) {
        if (userService.getUserById(id).isPresent()) {
            userService.deleteUser(id);
            return ResponseEntity.ok().build();
        }
        return ResponseEntity.notFound().build();
    }

    // ==================== 商家信息管理 ====================
    @GetMapping("/info")
    @Operation(summary = "获取商家信息")
    public ResponseEntity<Map<String, Object>> getMerchantInfo() {
        // 这里应该从SecurityContext获取当前商家信息
        Map<String, Object> merchantInfo = new HashMap<>();
        merchantInfo.put("id", 1L);
        merchantInfo.put("name", "示例洗衣店");
        merchantInfo.put("address", "北京市朝阳区示例街道123号");
        merchantInfo.put("phone", "010-12345678");
        merchantInfo.put("email", "merchant@example.com");
        merchantInfo.put("status", "ACTIVE");
        merchantInfo.put("rating", 4.5);
        merchantInfo.put("orderCount", 1250);
        
        return ResponseEntity.ok(merchantInfo);
    }

    @PutMapping("/info")
    @Operation(summary = "更新商家信息")
    public ResponseEntity<Map<String, Object>> updateMerchantInfo(
            @RequestBody Map<String, Object> merchantData) {
        
        // 这里应该实现商家信息更新逻辑
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "商家信息更新成功");
        return ResponseEntity.ok(response);
    }

    // ==================== 商家统计报表 ====================
    @GetMapping("/statistics")
    @Operation(summary = "获取商家统计数据")
    public ResponseEntity<Map<String, Object>> getMerchantStatistics(
            @RequestParam(required = false) String period) {
        
        Map<String, Object> statistics = new HashMap<>();
        
        // 订单统计
        LaundryOrderService.OrderStatistics orderStats = laundryOrderService.getOrderStatistics();
        statistics.put("orderStatistics", Map.of(
            "total", orderStats.getTotalOrders(),
            "today", orderStats.getTodayOrders(),
            "pending", orderStats.getPendingOrders(),
            "completed", 0L // 这里应该根据商家ID统计
        ));
        
        // 收入统计
        statistics.put("revenueStatistics", Map.of(
            "todayRevenue", orderStats.getTodayRevenue(),
            "monthlyRevenue", 0.0,
            "yearlyRevenue", 0.0
        ));
        
        // 客户统计
        statistics.put("customerStatistics", Map.of(
            "totalCustomers", 0L,
            "newCustomers", 0L,
            "activeCustomers", 0L
        ));
        
        return ResponseEntity.ok(statistics);
    }
}
